package top.abilities.util.token;

import com.fasterxml.jackson.core.JsonProcessingException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.abilities.util.token.entity.TokenVo;
import top.abilities.util.token.exceptions.TokenException;
import top.abilities.util.util.DateUtils;
import top.abilities.util.util.Jsons;
import top.abilities.util.util.RedisUtil;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * @author chenxueliang
 * @create 2019/4/29 15:19
 * @Desc
 **/
public class TokenRedis {
    private static final Logger logger = LoggerFactory.getLogger(TokenRedis.class);
    /**
     * 将令牌添加到缓存队列
     * @param token
     * @return  ticket令牌
     */
    public  String addToken(TokenVo token) throws JsonProcessingException {
        if (token == null){
            throw new NullPointerException("token不能为空。");
        }
        String ticket = createToken();
        token.setTokenValue(ticket);
        String tokenJson= Jsons.objToJson(token);
        logger.info(tokenJson);
        RedisUtil.set(ticket, tokenJson,15*24*60*60);
        logger.info("redis-get:"+RedisUtil.get(ticket));
        return ticket;

    }

    /**
     * 注销令牌
     */
    public static   void  deleteToken(String token){
        RedisUtil.remove(token);
    }

    /**
     * 令牌校验
     * @return
     */
    public  TokenVo checkToken(String tokenKey,String ip) throws IOException {
        //token是否存在
        if (tokenKey==null || tokenKey.trim() == ""){
            logger.error("token 不能空");
            return null;
        }
        if(!RedisUtil.exists(tokenKey) ){
            return  null;
        }
        //token是否过期
        logger.info(RedisUtil.get(tokenKey));
        TokenVo token =Jsons.jsonToObj(RedisUtil.get(tokenKey),TokenVo.class);

        if(token.getUpdateTime()!=null){
            Date tempDate = DateUtils.addSecond(token.getUpdateTime(),15*24*60*60);
            //过期,分比较
            if (DateUtils.compareDate(new Date(),tempDate,12)>0){
                throw  TokenException.TOKEN_EXPIRE;
            }
        }else{

        }

        //登录ip是否合法
        /*if(ip.compareTo(token.getIp()) != 0)
        {
            throw  TokenException.TOKEN_IP_NOT_SECURITY;
        }*/
        //更新token滑动有效时间
        token.setUpdateTime(new Date());
        //更新到redis
        RedisUtil.set(tokenKey,Jsons.objToJson(token),15*24*60*60);
        return token;
    }

    /**
     * 生成ticket键值
     * @return
     */
    public  String createToken(){
        String ticket = "gap-"+UUID.randomUUID().toString();
        return ticket;

    }
}
